<template>
  <div class="user-manager-container">
    <!-- 查询和上传操作栏 -->
    <div class="operation-bar">
      <div class="search-section">
        <el-input v-model="searchKeyword" placeholder="请输入关键词搜索" clearable style="width: 200px; margin-right: 10px;"
          @keyup.enter="handleSearch" />
        <el-button type="primary" @click="handleSearch">
          查询
        </el-button>
      </div>

      <div class="upload-section">
        <input type="file" ref="fileInput" @change="handleFileSelect" style="display: none" accept="*/*" />
        <el-button type="success" @click="triggerFileInput">
          选择文件
        </el-button>
        <el-button type="warning" @click="handleUpload" :disabled="!selectedFile">
          上传文件
        </el-button>
        <span v-if="selectedFile" style="margin-left: 10px; color: #666;">
          已选择: {{ selectedFile.name }}
        </span>
      </div>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="fileName" label="文件名" width="180" />
      <el-table-column prop="uploadTime" label="上传时间" width="180" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="userId" label="上传人" />
      <el-table-column label="内容" min-width="300">
        <template #default="{ row }">
          <div v-if="row.content" v-html="row.content"></div>
          <div v-else style="color: #999;"></div>
        </template>
      </el-table-column>
      <el-table-column prop="id" v-if="false" />
    </el-table>

    <!-- 删除按钮 - 固定在表格正下方中间 -->
    <div class="delete-button-container" v-show="selectedRows.length > 0">
      <el-button type="danger" @click="handleDelete" class="delete-button">
        删除选中文件
      </el-button>
    </div>
  </div>
</template>


<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listFile, uploadDocx, deleteDocs } from '@/js/ts_fetch'

// 表格数据
const tableData = ref([])

const searchKeyword = ref('')
// 选中的行数据
const selectedRows = ref([])
// 加载数据函数
const loadData = async () => {
  try {
    const res = await listFile({
      keyword: searchKeyword.value
    })
    if (res.code === 200 && res.data) {
      tableData.value = res.data
      console.log('用户数据加载成功:', tableData.value)
    } else {
      console.error('接口返回数据格式错误:', res.data)
      tableData.value = []
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}



onMounted(() => {
  loadData()
})



// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理删除操作
const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的文件')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个文件吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteDocs(selectedRows.value.map(row => row.id))
    // 重新加载数据
    const res = await listFile({
      keyword: searchKeyword.value
    })
    if (res.code === 200 && res.data) {
      tableData.value = res.data
      selectedRows.value = [] // 清空选中状态
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 查询操作
const handleSearch = () => {
  loadData()
}

// 文件上传相关
const fileInput = ref(null)
const selectedFile = ref(null)
// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}


// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
  }
}

const handleUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  try {
    const resp = await uploadDocx(selectedFile.value)
    if (resp.code !== 200) {
      throw new Error(resp.msg)
    }
    ElMessage.success('文件上传成功')

    // 清空文件选择
    selectedFile.value = null
    if (fileInput.value) {
      fileInput.value.value = ''
    }

    // 重新加载数据
    await loadData()
  } catch (error) {
    ElMessage.error(error.message)
  }
}
</script>


<style scoped>
.user-manager-container {
  position: relative;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.search-section,
.upload-section {
  display: flex;
  align-items: center;
}

.delete-button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px 0;
  position: sticky;
  bottom: 0;
  background: white;
  border-top: 1px solid #ebeef5;
}

.delete-button {
  width: 150px;
  height: 40px;
  font-size: 14px;
}
</style>